import http from "utils/request.js";
const publicFun = require('utils/public');

App({
    globalData: {
        baseURL: 'https://xzw.zone:8082',
        // baseURL: 'http://127.0.0.1:8000',
        appid: 'wxfd6cbcfc6ebff7ec',
        userInfo: '', //微信个人信息
        sysUserInfo: '', //系统用户信息
        userId: '',
        session_key: '',
        openid: '',
        hasUserInfo: false,
        vip: false,
        colorList: [{
                title: '嫣红',
                name: 'red',
                color: '#e54d42'
            },
            {
                title: '桔橙',
                name: 'orange',
                color: '#f37b1d'
            },
            {
                title: '明黄',
                name: 'yellow',
                color: '#fbbd08'
            },
            {
                title: '橄榄',
                name: 'olive',
                color: '#8dc63f'
            },
            {
                title: '森绿',
                name: 'green',
                color: '#39b54a'
            },
            {
                title: '天青',
                name: 'cyan',
                color: '#1cbbb4'
            },
            {
                title: '海蓝',
                name: 'blue',
                color: '#0081ff'
            },
            {
                title: '姹紫',
                name: 'purple',
                color: '#6739b6'
            },
            {
                title: '木槿',
                name: 'mauve',
                color: '#9c26b0'
            },
            {
                title: '桃粉',
                name: 'pink',
                color: '#e03997'
            },
            {
                title: '棕褐',
                name: 'brown',
                color: '#a5673f'
            },
            {
                title: '玄灰',
                name: 'grey',
                color: '#8799a3'
            },
            {
                title: '草灰',
                name: 'gray',
                color: '#aaaaaa'
            },
            {
                title: '墨黑',
                name: 'black',
                color: '#333333'
            },
            {
                title: '雅白',
                name: 'white',
                color: '#ffffff'
            },
        ]
    },

    onLaunch: function () {
        this.setCustomNavStyle()
        if (wx.getStorageSync('userInfo')) {
            this.globalData.userInfo = wx.getStorageSync('userInfo');
        }
        this.login();
    },

    onShow: function () {
        wx.hideTabBar({
            success: function () {
                //  app.onTabBar('user');
            }
        })
        this.updateApp();
    },

    //设置自定义导航栏样式
    setCustomNavStyle() {
        wx.getSystemInfo({
            success: e => {
                this.globalData.StatusBar = e.statusBarHeight;
                let capsule = wx.getMenuButtonBoundingClientRect();
                if (capsule) {
                    this.globalData.Custom = capsule;
                    this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
                } else {
                    this.globalData.CustomBar = e.statusBarHeight + 50;
                }
            }
        })
    },

    // 版本强制更新
    updateApp() {
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
                wx.showLoading({
                    title: '更新下载中...',
                })
            }
        })
        updateManager.onUpdateReady(function () {
            wx.hideLoading();
            wx.showModal({
                title: '更新提示',
                content: '新版本已上线，是否重启应用？',
                showCancel: false, //隐藏取消按钮
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })
        })
        updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.hideLoading();
            wx.showToast({
                title: '下载失败...',
                icon: "none"
            });
        })
    },

    // 登录
    login() {
        publicFun.wxLogin().then(res => {
            let data = {
                code: res
            };
            http.Request({
                url: 'getOpenId',
                method: 'GET',
                data: data
            }).then(async res => {
                if (res.code == 200) {
                    this.globalData.openid = res.data.openid
                    this.globalData.session_key = res.data.session_key
                    console.log('已登录');
                    this.getSysUser()
                }
            });
        })
    },

    // 获取用户信息
    getUserInfo(e) {
        return new Promise((resolve, reject) => {
            wx.getUserProfile({
                desc: '获取用户信息（头像、昵称等）',
                success: async res => {
                    this.globalData.userInfo = res.userInfo;
                    this.globalData.hasUserInfo = true;
                    resolve(this.globalData.userInfo)
                    if (this.globalData.userInfo) {
                        wx.setStorageSync('userInfo', res.userInfo);
                    } else {
                        wx.setStorageSync('userInfo', '');
                    }
                }
            })
        })
    },

    //查询用户是否存在
    getSysUser() {
        let data = {
            openId: this.globalData.openid
        }
        if (!this.globalData.openid) {
            this.login()
            return false
        }
        return new Promise((resolve, reject) => {
            http.Request({
                url: 'getUser',
                method: 'GET',
                data
            }).then(res => {
                if (res.code == 200) {
                    resolve(res.data);
                    let result = res.data
                    console.log('user', result);
                    if (result && result.length > 0) {
                        this.globalData.userId = result[0].id //存在时取用户id
                        this.globalData.sysUserInfo = result[0] //存在时取用户id
                        this.globalData.vip = result[0].vip
                        wx.switchTab({
                            url: '/page/index/index',
                        })
                    } else {
                        this.addUser()
                    }
                }
            });
        })
    },

    //新增用户
    addUser() {
        this.getUserInfo().then(userInfo => {
            console.log('userInfo', userInfo);
            let data = {
                nickName: userInfo.nickName,
                openId: this.globalData.openid,
                avatarUrl: userInfo.avatarUrl,
                gender: userInfo.gender,
                country: userInfo.country,
                province: userInfo.province,
                city: userInfo.city
            }
            http.Request({
                url: 'addUser',
                method: 'POST',
                data: data,
            }).then(re => {
                if (re.code == 200) {
                    this.getSysUser()
                }
            });
        })
    },
})